package org.linlinjava.litemall.admin.service;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallMemberRuleMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMemberMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.time.LocalDateTime;

/**
 * @author piao
 */
@Service
public class AdminMemberRuleService {
    @Resource
    private LitemallMemberRuleMapper memberRuleMapper;
    @Resource
    private LitemallUserMemberMapper userMemberMapper;

    /**
     * 新增会员规则
     * @param memberRule
     * @return
     */
    public Object createMemberRule(LitemallMemberRule memberRule) {
        memberRule.setAddTime(LocalDateTime.now());
        memberRule.setUpdateTime(LocalDateTime.now());
        String memberName = memberRule.getMemberName();
        LitemallMemberRuleExample example = new LitemallMemberRuleExample();
        example.or().andMemberNameEqualTo(memberName);
        LitemallMemberRule litemallMemberRule = memberRuleMapper.selectOneByExample(example);
        if (litemallMemberRule != null) {
            return ResponseUtil.fail(400,"您已创建该类型会员规则");
        }
        memberRuleMapper.insertSelective(memberRule);
        return ResponseUtil.ok();
    }

    /**
     * 修改会员规则
     * @param memberRule
     * @return
     */
    public Object updateMemberRule(LitemallMemberRule memberRule) {
        memberRule.setUpdateTime(LocalDateTime.now());

        return memberRuleMapper.updateByPrimaryKeySelective(memberRule);
    }

    /**
     * 删除会员规则
     * @param memberRuleId
     * @return
     */
    public Object deleteMemberRule(Integer memberRuleId) {
        LitemallUserMemberExample userMemberExample = new LitemallUserMemberExample();
        userMemberExample.or().andMemberRuleIdEqualTo(memberRuleId);
        userMemberMapper.selectByExample(userMemberExample);
        if (!userMemberMapper.selectByExample(userMemberExample).isEmpty()) {
            return ResponseUtil.fail(500,"该会员卡已有用户充值，不能删除");
        }
        memberRuleMapper.deleteByPrimaryKey(memberRuleId);
        return ResponseUtil.ok();
    }

    /**
     * 查询会员规则列表
     * @return
     */
    public Object listMemberRules() {
        LitemallMemberRuleExample memberRuleExample = new LitemallMemberRuleExample();
        return ResponseUtil.okList(memberRuleMapper.selectByExample(memberRuleExample));
    }

    /**
     * 获取一个详情
     * @param memberRuleId
     * @return
     */
    public Object findOne(Integer memberRuleId) {
        return ResponseUtil.ok(memberRuleMapper.selectByPrimaryKey(memberRuleId));
    }



}
